<template>
	<view class="login-page">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="navbar-left" @click="navigateBack">
				<uni-icons type="left" size="20" color="#333"></uni-icons>
			</view>
			<view class="navbar-title">账号登录</view>
			<view class="navbar-right" @click="gotoRegister">
				<text class="register-text">注册</text>
			</view>
		</view>

		<!-- 主内容区 -->
		<view class="content">
			<!-- 品牌Logo -->
			<view class="logo-container">
				<view class="logo">
					<text class="logo-text">KG</text>
				</view>
				<text class="app-name">酷狗音乐</text>
			</view>

			<!-- 登录方式切换 -->
			<view class="login-tabs">
				<view class="tab-item" :class="{ active: loginType === 'phone' }" @click="loginType = 'phone'">
					<text @click="()=>loginactive=0">手机号登录</text>
					<view class="tab-indicator" v-if="loginType === 'phone'"></view>
				</view>
				<view class="tab-item" :class="{ active: loginType === 'password' }" @click="loginType = 'password'">
					<text @click="()=>loginactive=1">密码登录</text>
					<view class="tab-indicator" v-if="loginType === 'password'"></view>
				</view>
			</view>

			<!-- 登录表单 -->
			<form @submit="handleLogin" class="login-form">
				<!-- 手机号/用户名输入 -->
				<view class="form-group">
					<view class="input-wrapper">
						<uni-icons :type="loginType === 'phone' ? 'contact' : 'person'" size="16" color="#999"
							class="input-icon"></uni-icons>
						<input :type="loginType === 'password' ? 'text' : 'text'" v-model="currentInput"
							:placeholder="loginType === 'phone' ? '请输入手机号' : '请输入用户名'" class="form-input"
							:maxlength="loginType === 'phone' ? 11 : 20">
					</view>
					<view v-if="errors.user" class="error-message">{{ errors.user }}</view>
					<view v-else class="error-message">{{ errors.phone }}</view>
				</view>

				<!-- 验证码/密码输入（手机号登录和密码登录时显示） -->
				<view class="form-group" v-if="loginType === 'phone' || loginType === 'password'">
					<view class="input-wrapper">
						<uni-icons :type="loginType === 'phone' ? 'verify' : 'locked'" size="16" color="#999"
							class="input-icon"></uni-icons>
						<input :type="loginType === 'phone' ? 'number' : 'password'" v-model="currentInput1"
							:placeholder="loginType === 'phone' ? '请输入验证码' : '请输入密码'" class="form-input"
							:maxlength="loginType === 'phone' ? 6 : 16">
						<!-- 验证码按钮 -->
						<button type="button" class="get-code-btn" v-if="loginType === 'phone'" @click="sendCode">
							{{ isCodeSending ? `${countdown}s` : '获取验证码' }}
						</button>
					</view>
					<view v-if="errors.password" class="error-message">{{ errors.password }}</view>
				</view>

				<!-- 记住密码（密码登录时显示） -->
				<view class="remember-password" v-if="loginType === 'password'">
					<view class="checkbox-wrapper">
						<checkbox v-model="form.rememberPassword" class="checkbox" color="#e5316f"></checkbox>
						<view class="remember-text">记住密码</view>
					</view>
					<text class="forgot-password" @click="gotoForgotPassword">忘记密码?</text>
				</view>

				<!-- 登录按钮 -->
				<button form-type="submit" class="login-btn" :loading="isLoading" @click="login">
					登录
				</button>
			</form>

			<!-- 其他登录方式 -->
			<view class="other-login">
				<view class="divider">
					<view class="divider-line"></view>
					<text class="divider-text">其他登录方式</text>
					<view class="divider-line"></view>
				</view>

				<view class="social-icons">
					<view class="icon-item" @click="loginWithWechat">
						<uni-icons type="weixin" size="28" color="#07C160"></uni-icons>
						<text class="icon-text">微信</text>
					</view>
					<view class="icon-item" @click="loginWithQQ">
						<uni-icons type="qq" size="28" color="#12B7F5"></uni-icons>
						<text class="icon-text">QQ</text>
					</view>
					<view class="icon-item" @click="loginWithWeibo">
						<uni-icons type="weibo" size="28" color="#E6162D"></uni-icons>
						<text class="icon-text">微博</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部信息 -->
		<view class="footer">
			<text class="footer-text">登录即表示同意</text>
			<text class="footer-link" @click="showAgreement">《用户服务协议》</text>
			<text class="footer-text">和</text>
			<text class="footer-link" @click="showPrivacy">《隐私政策》</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		watch,
		computed
	} from 'vue';
	import {
		useRouter
	} from 'vue-router';
	import {
		mimaloginAPI,
		phoneloginAPI
	} from '../../axios/http.js'

	const loginactive = ref(0)

	// 路由实例
	const router = useRouter();

	// 表单数据
	const form = reactive({
		user: '',
		password: '',
		phone: ''
	});

	let YZMcode = ref('')

	let code = ref('')

	// 错误信息
	const errors = reactive({
		user: '',
		password: '',
		phone: ''
	});

	// 状态管理
	const loginType = ref('phone'); // 'phone'（手机号登录）、'password'（密码登录）
	const isCodeSending = ref(false);
	const countdown = ref(60);
	const isLoading = ref(false);

	// 返回上一页
	const navigateBack = () => {
		uni.navigateBack({
			delta: 1
		});
	};

	// 前往注册页面
	const gotoRegister = () => {
		router.push('/components/register/register');
	};

	// 前往忘记密码页面
	const gotoForgotPassword = () => {
		router.push('/pages/forgot-password/forgot-password');
	};

	let YZMflag = ref(false)


	// 发送验证码
	const sendCode = () => {

		if (YZMflag.value) return;


		// 验证手机号
		if (!form.phone) {
			errors.phone = '请输入手机号';
			return;
		}

		const phoneReg = /^1[3-9]\d{9}$/;
		if (!phoneReg.test(form.phone)) {
			errors.phone = '请输入正确的手机号';
			return;
		}

		if (errors.phone == '') {
			YZMflag.value = true
		}


		// 清除错误
		errors.phone = '';

		// 模拟发送验证码
		isCodeSending.value = true;
		uni.showToast({
			title: '验证码已发送',
			icon: 'none'
		});

		// 倒计时
		const timer = setInterval(() => {
			countdown.value--;
			YZMflag.value = true
			if (countdown.value == 50) {
				for (var i = 0; i < 4; i++) {
					let codes = Math.floor(Math.random() * 9)
					code.value += codes
				}
				console.log('验证码为:' + code.value)
			}
			if (countdown.value <= 0) {
				clearInterval(timer);
				isCodeSending.value = false;
				countdown.value = 60;
				YZMflag.value = false
			}
		}, 1000);
	};

	// 验证表单
	const validateForm = () => {
		let isValid = true;

		// 验证手机号/用户名
		if (!form.user) {
			errors.user = loginType.value === 'phone' ? '请输入手机号' : '请输入用户名';
			isValid = false;
		} else if (loginType.value === 'phone' && !/^1[3-9]\d{9}$/.test(form.user)) {
			errors.user = '请输入正确的手机号';
			isValid = false;
		} else {
			errors.user = '';
		}

		验证验证码 / 密码
		if (!form.password) {
			errors.password = loginType.value === 'phone' ? '请输入验证码' : '请输入密码';
			isValid = false;
		} else if (loginType.value === 'phone' && form.password.length !== 6) {
			errors.password = '验证码长度为6位';
			isValid = false;
		} else if (loginType.value === 'password' && (form.password.length < 8 || form.password.length > 16)) {
			errors.password = '密码长度为8-16位';
			isValid = false;
		} else {
			errors.password = '';
		}

		return isValid;
	};

	// 微信登录
	const loginWithWechat = () => {
		isLoading.value = true;

		// 模拟微信登录
		setTimeout(() => {
			isLoading.value = false;
			uni.showToast({
				title: '微信登录成功',
				icon: 'success'
			});

			setTimeout(() => {
				router.push('/components/Home/Home?');
			}, 1000);
		}, 1500);
	};

	// QQ登录
	const loginWithQQ = () => {
		uni.showToast({
			title: 'QQ登录功能暂未开放',
			icon: 'none'
		});
	};

	// 微博登录
	const loginWithWeibo = () => {
		uni.showToast({
			title: '微博登录功能暂未开放',
			icon: 'none'
		});
	};

	const login = async () => {
		if (loginactive.value == 1) {
			let obj = {
				user: form.user,
				password: form.password
			}
			let res = await mimaloginAPI(obj)
			if (res.data.code == 200) {
				//在起始页面跳转到test.vue页面并传递参数
				uni.navigateTo({
					url: '/components/Home/Home?'
				});
				localStorage.setItem('token', res.data.token)
			} else {
				uni.showToast({
					title: '账号或密码错误，请重新填写',
					duration: 2000,
					icon: 'error'
				});
			}
		}
		if (loginactive.value == 0) {
			let obj = {
				phone: form.phone
			}
			let res = await phoneloginAPI(obj)
			if (res.data.code == 200 && YZMcode.value == code.value) {
				//在起始页面跳转到test.vue页面并传递参数
				uni.navigateTo({
					url: '/components/Home/Home?'
				});
				localStorage.setItem('token', res.data.token)
			} else {
				uni.showToast({
					title: '手机号或密码错误，请重新填写',
					duration: 2000,
					icon: 'error'
				});
			}
		}
	}

	// 页面加载时
	onMounted(() => {
		// 尝试获取保存的账号信息
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo && userInfo.user) {
			if (loginType.value === 'phone') {
				form.user = userInfo.user;
			}
		}
	});

	// 用计算属性处理条件判断
	const currentInput = computed({
		get() {
			// 根据 loginactive 决定返回哪个值
			return loginactive.value === 0 ? form.phone : form.user;
		},
		set(newValue) {
			// 根据 loginactive 决定更新哪个值
			if (loginactive.value === 0) {
				form.phone = newValue;
			} else {
				form.user = newValue;
			}
		}
	});

	// 用计算属性处理条件判断
	const currentInput1 = computed({
		get() {
			// 根据 loginactive 决定返回哪个值
			return loginactive.value === 1 ? form.password : YZMcode.value;
		},
		set(newValue) {
			// 根据 loginactive 决定更新哪个值
			if (loginactive.value === 0) {
				YZMcode.value = newValue;
			} else {
				form.password = newValue;
			}
		}
	});
</script>

<style scoped>
	.login-page {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 导航栏 */
	.navbar {
		display: flex;
		align-items: center;
		height: 44px;
		padding: 0 16px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.navbar-left {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.navbar-title {
		flex: 1;
		text-align: center;
		font-size: 17px;
		font-weight: 500;
		color: #333;
	}

	.navbar-right {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.register-text {
		color: #2183e4;
		font-size: 14px;
	}

	/* 主内容区 */
	.content {
		flex: 1;
		padding: 30px 24px 0;
	}

	/* Logo区域 */
	.logo-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30px;
	}

	.logo {
		width: 60px;
		height: 60px;
		background-color: #2183e4;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 10px;
	}

	.logo-text {
		color: #fff;
		font-size: 24px;
		font-weight: bold;
	}

	.app-name {
		font-size: 18px;
		color: #333;
		font-weight: 500;
	}

	/* 登录方式切换 */
	.login-tabs {
		display: flex;
		margin-bottom: 30px;
	}

	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.tab-item text {
		font-size: 16px;
		color: #999;
		padding-bottom: 8px;
	}

	.tab-item.active text {
		color: #2183e4;
		font-weight: 500;
	}

	.tab-indicator {
		width: 30px;
		height: 2px;
		background-color: #2183e4;
		border-radius: 1px;
	}

	/* 登录表单 */
	.login-form {
		margin-bottom: 30px;
	}

	.form-group {
		margin-bottom: 16px;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 8px;
		padding: 0 16px;
		height: 48px;
		border: 1px solid #eee;
	}

	.input-icon {
		margin-right: 12px;
	}

	.form-input {
		flex: 1;
		height: 100%;
		font-size: 14px;
		color: #333;
	}

	.form-input::placeholder {
		color: #ccc;
	}

	.get-code-btn {
		height: 32px;
		padding: 0 12px;
		background-color: #f5f5f5;
		color: #333;
		font-size: 14px;
		border-radius: 4px;
		line-height: 32px;
	}

	.get-code-btn:disabled {
		color: #999;
		background-color: #eee;
	}

	.error-message {
		color: #;
		font-size: 12px;
		margin-top: 4px;
		padding-left: 44px;
	}

	/* 记住密码 */
	.remember-password {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;
		font-size: 14px;
	}

	.checkbox-wrapper {
		display: flex;
		align-items: center;
	}

	.checkbox {
		width: 16px;
		height: 16px;
		margin-right: 6px;
	}

	.remember-text {
		margin-top: 4px;
		margin-left: 5px;
		color: #666;
	}

	.forgot-password {
		color: #2183e4;
	}

	/* 登录按钮 */
	.login-btn {
		width: 100%;
		height: 48px;
		background-color: #2183e4;
		color: #fff;
		font-size: 16px;
		border-radius: 8px;
		line-height: 48px;
	}

	.login-btn::after {
		border: none;
	}

	/* 其他登录方式 */
	.other-login {
		margin-top: 40px;
	}

	.divider {
		display: flex;
		align-items: center;
		margin-bottom: 24px;
	}

	.divider-line {
		flex: 1;
		height: 1px;
		background-color: #eee;
	}

	.divider-text {
		padding: 0 12px;
		font-size: 14px;
		color: #999;
	}

	.social-icons {
		display: flex;
		justify-content: center;
		gap: 36px;
	}

	.icon-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.icon-text {
		font-size: 12px;
		color: #666;
		margin-top: 8px;
	}

	/* 底部信息 */
	.footer {
		padding: 20px 16px;
		font-size: 12px;
		text-align: center;
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		gap: 4px;
	}

	.footer-text {
		color: #999;
	}

	.footer-link {
		color: #2183e4;
	}
</style>